<!-- eslint-disable @typescript-eslint/no-misused-promises -->
<script setup lang="ts">
  import { ref, h, onMounted } from 'vue'
  import {
    NIcon,
    NDatePicker,
    NInput,
    NDataTable,
    NPagination,
    NButton,
    useMessage,
  } from 'naive-ui'
  // import { useRouter } from 'vue-router'
  import {
    AccessTimeOutlined,
    CheckCircleFilled,
    CancelFilled,
    MoreHorizFilled,
  } from '@vicons/material'
  import { deleteSchemeAudit, downloadAuditReport, getSchemeAuditList } from '@/api/scheme'
  import dayjs from 'dayjs'
  import { useRouter } from 'vue-router'
  import { createChat } from '@/api/agent'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import DeleteModal from '@/components/common/DeleteModal/index.vue'
  import { useAgent } from '@/hooks/useAgent'
  import { generateMarkdown } from '@/utils/functions'
  import { getContent } from '@/views/Build/utils'
  const { userName } = useAgent()
  const date = ref(null)
  // const router = useRouter()
  const handleChange = async () => {
    page.value = 1
    await getList()
  }
  const data = ref([])

  const name = ref('')

  // 分页
  const page = ref(1)
  const pageSize = ref(10)
  const itemCount = ref(0)

  const handleUpdatePageSize = async (_pageSize: number) => {
    pageSize.value = _pageSize
    page.value = 1
    await getList()
  }

  const handleUpdatePage = async (_page: number) => {
    page.value = _page
    await getList()
  }
  const columns = [
    {
      title: '序号',
      key: 'index',
      render: (row: { index: number }) => {
        return row.index + 1 + (page.value - 1) * pageSize.value
      },
    },
    {
      title: '方案名称',
      key: 'schemeName',
    },
    {
      title: '文件大小',
      key: 'fileSize',
      render: (row: { fileSize: string }) => {
        return row.fileSize ?? '--'
      },
    },
    {
      title: '提交人',
      key: 'auditorId',
    },
    {
      title: '提交时间',
      key: 'createTime',
    },
    {
      title: '完成时间',
      key: 'updateTime',
    },
    {
      title: '审核结果',
      key: 'auditStatus',
      render: (row: { auditStatus: string }) => {
        let icon, text, color, bgColor

        if (+row.auditStatus === 1) {
          icon = CheckCircleFilled
          text = '审核通过'
          color = '#00B42A'
          bgColor = '#E8FFEA'
        } else if (+row.auditStatus === 2) {
          icon = CancelFilled
          text = '审核未通过'
          color = '#F5222D'
          bgColor = '#FFECE8'
        } else {
          icon = MoreHorizFilled
          text = '未审核'
          color = '#F77234'
          bgColor = '#FFF1EB'
        }

        return h(
          'div',
          {
            class: 'flex items-center w-fit gap-1 rounded px-2 h-[20px] leading-[20px] text-[12px]',
            style: {
              backgroundColor: bgColor,
            },
          },
          [
            h(
              NIcon,
              {
                size: 16,
                color,
                class:
                  +row.auditStatus === 0
                    ? 'rounded-full bg-[#F77234] !text-[#fff] !text-[14px]'
                    : '',
              },
              { default: () => h(icon) }
            ),
            h('div', { style: { color } }, { default: () => text }),
          ]
        )
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (row: {
        auditStatus: string
        id: string
        schemeUrl: string
        isLoading: boolean
        schemeName: string
      }) => {
        return h('div', { class: 'flex items-center' }, [
          h(
            NButton,
            {
              quaternary: true,
              type: 'info',
              class: '!px-2',
              disabled: row.isLoading,
              onClick: (): any => handleView(row),
            },
            { default: () => '查看' }
          ),
          h(
            NButton,
            {
              quaternary: true,
              type: 'info',
              class: '!px-2',
              disabled: +row.auditStatus === 0,
              onClick: () => handleReAudit(row),
            },
            {
              default: () =>
                row.isLoading
                  ? h('div', { class: 'flex items-center' }, [
                      h('span', { class: 'mr-1' }, { default: () => '重新审核中' }),
                      h(SvgIcon, {
                        class: 'text-[#0B5CFF] text-[12px] flex items-center',
                        name: 'loading',
                      }),
                    ])
                  : h('span', { class: 'flex item-center' }, { default: () => '重新审核' }),
            }
          ),
          h(
            NButton,
            {
              quaternary: true,
              type: 'info',
              class: '!px-2',
              disabled: +row.auditStatus === 0 || row.isLoading,
              onClick: () => handleDownload(row),
            },
            { default: () => '下载报告' }
          ),
          h(
            NButton,
            {
              quaternary: true,
              type: 'info',
              class: '!px-2',
              disabled: row.isLoading,
              onClick: () => beforeHandleDelete(row),
            },
            { default: () => '删除' }
          ),
        ])
      },
    },
  ]
  const router = useRouter()
  const handleView = async (row: { id: string; auditStatus: string }) => {
    if (+row.auditStatus === 1) {
      await router.push(`/createGenerateResult/${row.id}`)
    } else if (+row.auditStatus === 2) {
      await router.push(`/createAuditPass/${row.id}/2`)
    }
  }

  const handleDownload = async (row: { id: string }) => {
    const res = await downloadAuditReport({ id: row.id })
    const { content: answerContent } = getContent(res)
    generateMarkdown(answerContent, '审核报告.md')
  }

  const handleReAudit = async (row: { id: string; schemeUrl: string; isLoading: boolean }) => {
    if (row.schemeUrl) {
      row.isLoading = true
      const res = await createChat({
        query: '帮我检修一个方案',
        userName,
        responseMode: 'blocking',
        inputs: {
          file_path: row.schemeUrl,
        },
      }).finally(() => {
        row.isLoading = false
      })
      console.log(res)
    }
  }

  const beforeHandleDelete = (row: { id: string; schemeName: string }) => {
    deleteId.value = row.id
    deleteModalRef.value.showModal(`确定要删除方案“${row.schemeName}”吗？`)
  }
  const deleteId = ref('')
  const deleteModalRef = ref()
  const message = useMessage()
  const handleDelete = async () => {
    await deleteSchemeAudit({ id: deleteId.value }).finally(() => {
      deleteId.value = ''
      message.success('删除成功')
    })
    await getList()
  }
  const getList = async () => {
    const res = await getSchemeAuditList({
      pageNum: page.value,
      pageSize: pageSize.value,
      type: 2,
      schemeName: name.value ?? undefined,
      startTime: date.value?.[0] ? dayjs(date.value[0]).format('YYYY-MM-DD 00:00:00') : undefined,
      endTime: date.value?.[1] ? dayjs(date.value[1]).format('YYYY-MM-DD 23:59:59') : undefined,
    })
    res.list.forEach((item: any, index: number) => {
      item.index = index
      item.isLoading = false
    })
    data.value = res.list
    itemCount.value = res.total
  }

  onMounted(async () => {
    await getList()
  })
</script>

<template>
  <div class="h-full bg-white rounded p-5">
    <div class="flex flex-col h-full">
      <!-- 条件筛选 -->
      <div class="h-8 leading-8 flex items-center gap-4">
        <div class="flex items-center">
          <div class="text-[#4A5055]">时间：</div>
          <div class="flex items-center">
            <n-date-picker
              v-model:value="date"
              type="daterange"
              @update:value="handleChange"
              size="small"
              class="w-[400px]"
              clearable
            >
              <template #date-icon>
                <n-icon :size="16">
                  <AccessTimeOutlined />
                </n-icon>
              </template>
            </n-date-picker>
          </div>
        </div>
        <div class="flex items-center">
          <div class="text-[#4A5055]">文档名称：</div>
          <div class="flex items-center">
            <n-input
              @keyup.enter="handleChange"
              class="!w-[240px]"
              v-model:value="name"
              placeholder="请输入文档名称"
              size="small"
            />
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="flex-1 mt-6 flex flex-col">
        <n-data-table
          class="min-h-[500px] max-h-[calc(100%-56px)] overflow-y-auto"
          :columns="columns"
          :data="data"
          :pagination="false"
          :bordered="false"
        />
        <div class="h-8 mt-6 flex justify-end items-center">
          <n-pagination
            show-quick-jumper
            v-model:page="page"
            :page-size="pageSize"
            :item-count="itemCount"
            :page-sizes="[10, 20, 50]"
            show-size-picker
            :on-update-page-size="handleUpdatePageSize"
            :on-update-page="handleUpdatePage"
          >
            <template #prefix="{ itemCount }">
              <span class="pingfang text-[#666D7A]">共 {{ itemCount }} 条</span>
            </template>
            <template #suffix>
              <span class="pingfang text-[#666D7A]">页</span>
            </template>
          </n-pagination>
        </div>
      </div>
    </div>

    <delete-modal ref="deleteModalRef" @submit="handleDelete" />
  </div>
</template>

<style lang="less" scoped></style>
